<template>
	<view>
		<!-- 主体 -->
		<view class="page page-register">
			<!-- 卡片 -->
			<view class="card-img bg-cover"
				:style="{backgroundImage: 'url(' + (cardInfo.card_img ? cardInfo.card_img : '') + ')'}"></view>
			<!-- 注册信息 -->
			<view class="register-box">
				<template v-if="mode == 'create'">
					<view class="item">
						<view class="label">姓&nbsp;&nbsp;&nbsp;&nbsp;名：</view>
						<input v-model="form.name" type="text" placeholder="请输入姓名" placeholder-class="placeholderClass"
							@input="Onname" />
					</view>
					<view class="item">
						<view class="label">手机号：</view>
						<input v-model="form.mobile" type="number" placeholder="请输入手机号码"
							placeholder-class="placeholderClass" @input="Onmobile" />
					</view>
					<view class="item">
						<view class="label">验证码：</view>
						<input v-model="form.code" type="number" placeholder="请输入验证码"
							placeholder-class="placeholderClass" @input="Oncode" />
						<button class="getcode" :disabled="wait > 0" @click.stop="getVerifyCode">
							<text v-if="wait > 0">等待{{wait}}秒</text>
							<text v-else>获取验证码</text>
						</button>
					</view>
					<view class="item">
						<view class="label">性&nbsp;&nbsp;&nbsp;&nbsp;别：</view>
						<uni-data-checkbox class="flex-1" v-model="form.gender" :localdata="gender.range"
							:selectedColor="themeColor" selectedTextColor="#1e1e1e" @change="Onsex">
						</uni-data-checkbox>
					</view>
					<view class="item">
						<view class="label">生&nbsp;&nbsp;&nbsp;&nbsp;日：</view>
						<view class="flex-1 date">
							<biaofun-datetime-picker placeholder="请选择生日" :defaultValue="form.birthday"
								:start="calendar.start" :end="calendar.end" fields="day"
								@change="Onbirthday"></biaofun-datetime-picker>
						</view>
						<uni-icons type="arrowright" size="12" :color="themeColor"></uni-icons>
					</view>
				</template>

				<!-- 协议 -->
				<view class="check-box flex-row-start" :class="{ checked: agreement }" @click="toggleCheck">
					<view class="inner"></view>
					<text class="info">我已经阅读并同意</text>
					<text class="info font-link" @click.stop="openAgree">《璞廷会会员协议》</text>
				</view>
				<view @click="Onfictitious(item)" class="check-box flex-row-start"
					:class="fictitious_id == item.id?'checked':''" v-for="(item,index) in fictitious_list" :key="index">
					<view class="inner"></view>
					<text class="info font-link" @click.stop="openAgree2(item)">{{item.name}}</text>
					<text class="info">{{item.price}}元</text>
				</view>
				<!-- 				<view v-if="cardInfo.coupon_activity_info" @click="OncouponActivity" class="check-box flex-row-start"
					:class="coupon_activity_id == cardInfo.coupon_activity_info.id?'checked':''">
					<view class="inner"></view>
					<text class="info font-link">{{cardInfo.coupon_activity_info.name}}</text>
				</view> -->
				<!-- 注册按钮 -->
				<view :class="{'register-btns flex-row-between' : cardInfo.price != '0.00'}">
					<view class="spot" v-show="cardInfo.price != '0.00'">
						<text>应付：</text>
						<text class="font-assist">￥{{Onprice(cardInfo.price , fictitious_price)}}</text>
					</view>

					<!--  #ifdef  MP-WEIXIN -->
					<view class="btn font15 font-ffffff flex-row-center" @click="submit()">
						{{mode == 'update' ? '立即升级' : '立即注册'}}
					</view>
					<!--  #endif -->

					<!--  #ifdef  H5 -->
					<view class="btn font15 font-ffffff flex-row-center" @click="submit()">
						{{mode == 'update' ? '立即升级' : '立即注册'}}
					</view>
					<!--  #endif -->
				</view>
			</view>
		</view>
		<!-- 协议弹窗 -->
		<uni-popup ref="rule" type="center">
			<view class="popup-rule">
				<view class="title font15 tc">璞廷会会员协议</view>
				<scroll-view class="content" :scroll-y="true">
					<rich-text :nodes="agreementRich"></rich-text>
				</scroll-view>
				<view class="btn-long" @click="closeAgree">知道了</view>
			</view>
		</uni-popup>
		<!-- 协议弹窗2 -->
		<uni-popup ref="rule2" type="center">
			<view class="popup-rule">
				<view class="title font15 tc">增值权益</view>
				<scroll-view class="content" :scroll-y="true">
					<rich-text :nodes="rule2s"></rich-text>
				</scroll-view>
				<view class="btn-long" @click="closeAgree2">知道了</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import biaofunDatetimePicker from '@/components/biaofun-datetime-picker/index.vue';
	export default {
		components: {
			biaofunDatetimePicker
		},
		data() {
			return {
				cardId: null,
				themeColor: '#03004c',
				calendar: {
					defaultValue: this.$base.formatTime(new Date(), "yyyy-MM-dd"),
					start: '1940-01-01',
					end: this.$base.formatTime(new Date(), "yyyy-MM-dd")
				},
				// 性别
				gender: {
					value: '1',
					range: [{
							value: '1',
							text: "男"
						},
						{
							value: '2',
							text: "女"
						}
					]
				},
				cardInfo: {}, // 需要注册的会员卡的信息
				userInfo: {}, // 用户信息（针对升级的用户）
				idInfo: {},
				idInfo_origin: {}, // 原始的id信息
				agreement: false, // 是否接受协议
				agreementRich: '', // 协议内容
				wait: 0, // 验证码等待的时间
				timer: null,
				form: {
					type: 'member',
					group: this.group,
					name: '',
					mobile: '',
					code: '',
					gender: '1',
					birthday: this.$base.formatTime(new Date(), "yyyy-MM-dd"),
					crs_level: '',
					parent_id: '', // 父id
					channel: '', // 渠道（用于活动）
					source: '', // 来源id
				},
				mode: '', // 注册create，升级update
				wxSdk: false, // h5是否签名成功（此页面用于支付）
				h5share: true, // 当前页面是否单独获取签名
				fictitious_id: '', //升级权益
				fictitious_list: [],
				fictitious_price: 0,
				rule2s: '',
				fictitious_two_id: '',
				coupon_activity_id: '',
			}
		},
		onLoad(options) {
			this.fictitious_two_id = options.tid ? options.tid : ''
			this.coupon_activity_id = options.aid ? options.aid : ''
			let $param = uni.getStorageSync("updateInfo");
			// 类型：注册/升级
			this.mode = $param.mode

			// 从缓存中拿取各种id信息
			this.idInfo = uni.getStorageSync('idInfo')
			this.idInfo_origin = uni.getStorageSync('idInfo_origin')

			// #ifdef H5
			if (options.id) {
				this.mode = 'create'
				this.cardId = options.id
			}
			this.form.openid = uni.getStorageSync("openid");
			// 获取微信签名，用于支付
			this.$wxapi.OnwxSdk().then(res => {
				if (res.code == 1) {
					this.wxSdk = true
					this.Onshare()
				} else {
					this.wxSdk = false
				}
			})
			// #endif

			// 获取会员卡信息
			this.$Http({
				token: this.mode == 'create' ? false : true,
				url: 'card',
				data: {
					id: $param.cardId ? $param.cardId : this.cardId,
					type: this.mode == 'create' ? 1 : 2
				}
			}).then(res => {
				res.data.card_img = this.$Config.http_static + res.data.card_img
				this.cardInfo = res.data
				this.form.crs_level = res.data.crs_level
				this.fictitious_list = res.data.fictitious_list

				if (res.data.fictitious_list.length > 0) {
					if (res.data.id == 4) {
						this.Onfictitious(res.data.fictitious_list[0])
					}
				}

			});

			// 获取用户信息
			let $token = uni.getStorageSync("token");
			if ($token) {
				this.$Http({
					url: 'user',
					token: true
				}).then(res => {
					if (res.code == 1) {
						this.form.name = res.data.user.name
						this.form.mobile = res.data.user.mobile
						this.form.gender = res.data.user.gender.toString()
						this.form.birthday = res.data.user.birthday
						this.userInfo = res.data
					}
				});
			}

			// 获取协议
			this.$Http({
				url: 'agreement'
			}).then(res => {
				if (res.code == 1) {
					this.agreementRich = res.data
				}
			});
		},
		onShow: function() {
			// #ifdef MP-WEIXIN
			wx.login({
				success: res => {
					console.log(res.code,'res.code')
					this.form.wx_code = res.code
				}
			})
			// #endif
		},
		methods: {
			Onname(e) {
				this.form.name = e.detail.value
			},
			Onmobile(e) {
				this.form.mobile = e.detail.value
			},
			Oncode(e) {
				this.form.code = e.detail.value
			},
			Onsex(e) {
				this.form.gender = e.detail.value
			},
			Onbirthday(date) {
				this.form.birthday = date.f1
			},
			// 获取手机验证码
			getVerifyCode() {
				if (this.$base.checkMobile(this.form.mobile)) {
					this.$Http({
						url: 'sendCode',
						data: {
							mobile: this.form.mobile,
							event: this.mode == 'update' ? 'login' : 'register'
						},
					}).then(res => {
						if (res.code == 1) {
							uni.showToast({
								title: '验证码发送成功'
							})
							this.wait = 60
							this.timer = setInterval(() => {
								this.wait--
								if (this.wait === 0) {
									clearInterval(this.timer)
								}
							}, 1000)
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
						}
					});
				} else {
					uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					})
				}
			},
			// 协议勾选
			toggleCheck() {
				this.agreement = !this.agreement
			},
			Onfictitious(item) {
				if (this.fictitious_id == item.id) {
					this.fictitious_id = null
					this.fictitious_price = 0
				} else {
					this.fictitious_id = item.id
					this.fictitious_price = item.price
				}
			},
			Onprice(value1, value2) {
				let text = 0
				text = (value1 * 100) + (value2 * 100)
				text = text / 100
				text = text.toFixed(2)
				return text
			},
			// 打开协议
			openAgree() {
				this.$refs.rule.open()
			},
			openAgree2(res) {
				this.rule2s = res.content
				this.$refs.rule2.open()
			},
			// 关闭协议
			closeAgree() {
				this.$refs.rule.close()
			},
			closeAgree2() {
				this.$refs.rule2.close()
			},
			// 提交表单
			submit() {
				let that = this

				if (this.mode == 'create') {
					if (this.form.name == '') {
						uni.showToast({
							title: '请输入您的姓名',
							icon: 'none'
						});
						return false;
					}
					if (!this.$base.checkMobile(this.form.mobile)) {
						uni.showToast({
							title: '请输入正确的手机号码',
							icon: 'none'
						})
						return
					}
					if (this.form.code == '') {
						uni.showToast({
							title: '请输入验证码',
							icon: 'none'
						});
						return false;
					}
					if (this.form.birthday == '') {
						uni.showToast({
							title: '请选择您的生日',
							icon: 'none'
						});
						return false;
					}
				}

				if (!this.agreement) {
					uni.showToast({
						title: '请阅读并同意会员协议',
						icon: 'none'
					});
					return false;
				}

				// 父级id 和 来源id 一样
				this.form.parent_id = this.idInfo.Fid;
				this.form.source = this.idInfo.Fid;
				this.form.channel = this.idInfo.Cid ? this.idInfo.Cid : '';
				let registerData = this.form
				registerData.fictitious_two_id = this.fictitious_two_id
				registerData.coupon_activity_id = this.coupon_activity_id

				let updateData = {
					p_user_id: this.idInfo_origin ? this.idInfo_origin.Fid : this.idInfo.Pid,
					crs_level: this.cardInfo.crs_level,
					code: this.form.code,
					fictitious_id: this.fictitious_id ? this.fictitious_id : '',
				}
				

				this.$Http({
					url: this.mode == 'update' ? 'cardUpgrade' : 'register',
					data: this.mode == 'update' ? updateData : registerData,
					token: this.mode == 'update' ? true : false,
					type: this.mode == 'update' ? 'GET' : 'POST',
				}).then(res => {
					// 重新获取code
					wx.login({
						success: res => {
							that.form.wx_code = res.code
						}
					})
					if (res.code == 1) {
						uni.setStorage({
							key: 'token',
							data: res.data.token
						})
						if (that.cardInfo.price != '0.00') {
							if (res.data.order_id != '') {
								// 获取支付参数
								let $obj = {
									type: 'card',
									order_id: res.data.order_id,
									os: that.group == 'wxapp' ? 'WxApp' : 'H5'
								}
								// #ifdef H5
								$obj.openid = that.form.openid
								// #endif
								// #ifdef MP-WEIXIN
								$obj.code = that.form.wx_code
								// #endif
								that.$Http({
									url: 'paySign',
									data: $obj,
								}).then(res1 => {
									if (res1.code == 1) {
										that.Onpay(res1.data)
									} else {
										uni.showToast({
											title: res1.msg,
											icon: 'none'
										});
									}
								});
							} else {
								that.$base.Onpageurl()
							}
						} else {
							that.$base.Onpageurl()
						}
					} else if (res.code == 500) {
						uni.showToast({
							title: '接口异常，请稍后再试',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				});
			},
			// 支付
			Onpay(param) {
				var that = this
				// #ifdef MP-WEIXIN
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: param.timeStamp,
					nonceStr: param.nonceStr,
					package: param.pacKage,
					signType: 'MD5',
					paySign: param.paySign,
					success: function(res) {
						uni.showToast({
							title: '支付成功'
						});
						uni.removeStorageSync("idInfo_origin");
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/my/index'
							})
						}, 2000)
					},
					fail: function(err) {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/my/index'
							})
						}, 2000)
					}
				});
				// #endif
				// #ifdef H5
				if (that.wxSdk) {
					this.$wxapi.OnWXPay(param).then(res => {
						console.log('OnWXPay返回：' + JSON.stringify(res))
						if (res.code == 1) {
							uni.showToast({
								title: '支付成功'
							});
						} else if (res.code == 0) {
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							});
						} else if (res.code == 3) {
							uni.showToast({
								title: '支付取消',
								icon: 'none'
							});
						}
						setTimeout(() => {
							uni.switchTab({
								url: '/pages/my/index'
							})
						}, 2000)
					})
				} else {
					uni.showToast({
						title: '微信签名失败',
						icon: 'none'
					});
				}
				// #endif
			}
		}
	}
</script>

<style lang="less">
	@import url("style.less");
</style>